package com.laoye.aspect;

import com.laoye.annotation.Log;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Component
public class aspect {
    @Pointcut("@annotation(com.laoye.annotation.Log)")
    public void logPointcut(){}

    @Around("logPointcut()")
    public Object log(ProceedingJoinPoint joinPoint) throws Throwable{
        Long startTime = System.currentTimeMillis();

        MethodSignature signature =(MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        Log annotation = method.getAnnotation(Log.class);
        String desc = annotation.value();   //获取注解中的方法描述
        boolean printParam = annotation.printParam();

        System.out.println("---------------------方法监控开始---------------------");
        System.out.println("方法描述："+(desc.isEmpty()?"无描述" : desc));
        System.out.println("方法名："+method.getDeclaringClass().getName()+"."+method.getName());
        System.out.println("参数列表："+ (printParam ?Arrays.toString(joinPoint.getArgs()):"无参数"));


        Object result = joinPoint.proceed();
        Long endTime = System.currentTimeMillis();
        System.out.println("方法返回值："+result);
        System.out.println("方法执行耗时："+(endTime-startTime)+"ms");
        System.out.println("---------------------方法监控结束---------------------");
        return  result ;
    }
}
